package com.sdgakj.service.feed;

import com.google.common.collect.Maps;
import com.sdgakj.dto.FeedCommentDTO;
import com.sdgakj.dto.FeedDTO;
import com.sdgakj.dto.FeedMsgDTO;
import com.sdgakj.dto.base.ResCode;
import com.sdgakj.entity.*;
import com.sdgakj.enums.EnumIsDelete;
import com.sdgakj.repository.*;
import com.sdgakj.service.ServiceException;
import com.sdgakj.service.person.PersonService;
import com.sdgakj.service.user.UserService;
import com.sdgakj.utils.JsonMapper;
import com.sdgakj.utils.SchoolSearchFilter;
import com.sdgakj.utils.SchoolSpecifications;
import org.apache.commons.codec.language.bm.Languages;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.mapper.BeanMapper;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;

import java.math.BigDecimal;
import java.util.*;

@Component
@Transactional
public class FeedService {

	private static final String location = null;

	@Autowired
	private FeedDao feedDao;
	
	@Autowired
	private FeedTagDao feedTagDao;
	
	@Autowired
	private FeedCommentDao feedCommentDao;
	
	@Autowired
	private FeedLikeDao feedLikeDao;

	@Autowired
	private FeedMsgDao feedMsgDao;

    @Autowired
    private UserService userService;

	@Autowired
	private PersonService personService;
//	@Autowired
//	private MessageUserService messageUserService;
//	@Autowired
//	private MessageService messageService;
	
	public Feed getFeedById(Long id) {
		Feed feeds = feedDao.findOne(id);
				return feedDao.findOne(id);
	}
	public List<Feed> getFeedListByUser(Long userId){
		return  feedDao.getFeedListByUser(userId);
	}
	
	public List<Feed> getFeedList() {
		return (List<Feed>) feedDao.findAll();
	}
	
	public List<Feed> getFeedList(String sortName,String sortType) {
		Sort sort = buildSortRequest(sortName,sortType);
		return (List<Feed>) feedDao.findAll(sort);
	}
	
	public void saveFeed(Feed entity) {
		feedDao.save(entity);
	}
	
	public void updateFeed(Feed entity) {
		feedDao.save(entity);
	}
	
	/**
	 * 创建新贴
	 * @param entity 实体：content，pics
	 * @param loginName 发布人loginName
	 */
	public void createFeed(Feed entity,String loginName){
		entity.setCreateDate(new Date());
		entity.setUpdateDate(new Date());
		entity.setState(Integer.parseInt(EnumIsDelete.NOTDELETE.getCode()));
		entity.setDeltag(EnumIsDelete.NOTDELETE.getCode());
		entity.setViewCount(0);
		entity.setLikeCount(0);
		entity.setCommentCount(0);
		entity.setShareCount(0);
		entity.setReportCount(0);
		User customer =userService.getUserByLoginName(loginName);
		if(customer ==null){
			throw new ServiceException(ResCode.MGR_FEED_EMPTY_CUSTOMER);
		}
		entity.setUserId(customer.getId()); //设置发帖用户
		feedDao.save(entity);
	}
	
	public List<Feed> getFeedByName(String name) {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		if (StringUtils.isNotBlank(name)) {
			filters.put("name", new SearchFilter("name", Operator.EQ, name));
		}
		Specification<Feed> spec = DynamicSpecifications.bySearchFilter(filters.values(), Feed.class);
		return feedDao.findAll(spec);
	}
	
	public void deleteFeed(Long id) {
		Feed feed = this.getFeedById(id);
//		feed.setState(EnumIsDelete.DELETED.getCode());
		feed.setDeltag(EnumIsDelete.DELETED.getCode());
		feed.setUpdateDate(new Date());
		feed.setIsTop(false);
		feed.setTopDate(null);
		this.saveFeed(feed);
		
		StringBuilder content = new StringBuilder();
		content.append("【");
		content.append(feed.getCreateDate());
		content.append("】  【");
		content.append(feed.getFeedTag().getName());
		content.append("】 信息 【");
		content.append(feed.getContent());
		content.append("】");
		FeedMsg msg = new FeedMsg(id, feed.getUserId(),
				1, 1, content.toString(), new Date());
		feedMsgDao.save(msg);
	}
	
	public List<Feed> getFeedByDeltag(String deltag,String sortName,String sortType) {
		Map<String, SearchFilter> filters = Maps.newHashMap();
		if (StringUtils.isNotBlank(deltag)) {
			filters.put("deltag", new SearchFilter("deltag", Operator.EQ, deltag));
		}
		Specification<Feed> spec = DynamicSpecifications.bySearchFilter(filters.values(), Feed.class);
		Sort sort = buildSortRequest(sortName,sortType);
		return feedDao.findAll(spec, sort);
	}

	public Page<Feed> getFeedByPage(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortName,
			String sortType) {
		PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortName, sortType);
		Specification<Feed> spec = buildSpecification(searchParams);
		return feedDao.findAll(spec, pageRequest);
	}

	/**
	 * 创建排序.
	 */
	private Sort buildSortRequest(String sortName,String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.DESC, "id");
		}else if("desc".equals(sortType)){
			sort = new Sort(Direction.DESC, sortName);
		}else{
			sort = new Sort(Direction.ASC, sortName);
		}
		return sort;
	}
	
	/**
	 * 创建分页请求.
	 */
	private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortName, String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.DESC,"isTop", "topDate", "id");
		}else if("desc".equals(sortType)){
			sort = new Sort(Direction.ASC,"seq");
		}
		return new PageRequest(pageNumber - 1, pagzSize, sort);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<Feed> buildSpecification(Map<String, Object> searchParams) {
		Map<String, SchoolSearchFilter> filters = SchoolSearchFilter.parse(searchParams);
		Specification<Feed> spec = SchoolSpecifications.bySearchFilter(filters.values(),Feed.class);
		return spec;
	}
	
	/**
	 * 获取时间轴帖子
	 * 
	 * @param customerId
	 * @param tagId
	 * @param sinceId
	 * @param maxId
	 * @param pageSize
	 * @return
	 */
    public List<FeedDTO> getListTimeline(Long customerId, Long tagId, Long sinceId, Long maxId,
			Integer pageSize) {
    	 List<Feed> allFeeds = new ArrayList<Feed>();
    	 //如果是首次下拉请求
    	 if((sinceId == null || sinceId == 0l) && (maxId == null || maxId == 0l)) {
    		 List<Feed> topFeeds = feedDao.getTopFeeds();
    		 //把置顶的feed先加入list中
    		 allFeeds.addAll(topFeeds);
    	 }
    	 //后面的按照id倒叙
    	 List<Feed> feeds = feedDao.findTimeline(null, tagId, 0, sinceId, maxId, pageSize);
    	 allFeeds.addAll(feeds);
    	 return feedsProcess(customerId, allFeeds);
	}
    
    /**
	 * 获取我的时间轴帖子
	 * 
	 * @param customerId
	 * @param tagId
	 * @param sinceId
	 * @param maxId
	 * @param pageSize
	 * @return
	 */
    public List<FeedDTO> getMyListTimeline(Long customerId, Long tagId, Long sinceId, Long maxId,
			Integer pageSize) {
    	 List<Feed> feeds = feedDao.findTimeline(customerId, tagId, null, sinceId, maxId, pageSize);
    	 return feedsProcess(customerId, feeds);
	}

	public List<FeedDTO> getMyList(Long userId, Long tagId, Long fId) {
		List feeds = this.feedDao.findByUserIdAndTagIdAndFId(userId, tagId, fId);
		return this.feedsProcess(userId, feeds);
	}

	public List<FeedDTO> getMyList(Long userId, Long tagId) {
		List feeds = this.feedDao.findByUserIdAndTagId(userId, tagId);
		return this.feedsProcess(userId, feeds);
	}
	public List<Feed> getFeedlist(String tit){
		return  this.feedDao.getFeedLikeTitle(tit);
	}

	/*
	* @return 家族的List<FeedDTO>
	* */
	public List<FeedDTO> getFamilyList(Long userId,Long familyId,Long tagId){
		List<Feed> list=feedDao.findByFamilyAndTagId(familyId,tagId);
		return feedFamily(userId,list);
	}



	public FeedDTO getFeedOne(Long userId,Long feedId){
		Feed feed=this.feedDao.findOne(feedId);
		return this.feedProcess(userId,feed);
	}
    private List<FeedDTO> feedsProcess(Long customerId, List<Feed> feeds) {
    	List<FeedDTO> result = new ArrayList<FeedDTO>();
    	if(feeds != null && !feeds.isEmpty()) {
    		for (Feed feed : feeds) {
    			FeedDTO feedDTO = BeanMapper.map(feed, FeedDTO.class);
				User user=userService.getUserById(feed.getUserId());
    			feedDTO.getCustomer().setMobile(user.getMobile());
				feedDTO.getCustomer().setName(user.getName());
				Person person=personService.getPersonByUserId(user.getId());
				if(person!=null) {
				//	System.out.println(person);
					feedDTO.getCustomer().setPic(person.getAvatar());
				}
    			//处理pic
    			String picStr = feed.getPics();
    			if(StringUtils.isNotBlank(picStr)) {
    				String[] pics = picStr.split("\\|");
    				if(pics.length > 0) {
    					feedDTO.setPicList(pics);
    				}
    			}
    			//处理comment
    	/*		String commentsStr = feed.getComments();
				if(commentsStr!=null) {
					List<FeedCommentDTO> commentDTOs = new ArrayList<FeedCommentDTO>();
					if (StringUtils.isNotBlank(commentsStr)) {
						JsonMapper mapper = JsonMapper.nonDefaultMapper();
						commentDTOs = (List<FeedCommentDTO>) mapper.fromJson(commentsStr, mapper.contructCollectionType(List.class, FeedCommentDTO.class));
					}
					feedDTO.setTopCommentList(commentDTOs);
				}*/

				//处理comment
				Integer count=feedCommentDao.getFeedCommentCount(feed.getId());
				feedDTO.setCommentCount(count);

    			//处理liked
				feedDTO.setLiked(false);
				if(customerId != null) {
					FeedLike like = feedLikeDao.findByUserIdAndFeedId(customerId, feed.getId());
					if(like != null) {
						feedDTO.setLiked(true);
					} 
				}
				feedDTO.setCreateTime(feed.getCreateDate());
				//feedDTO.setCommentCount(feed.getCommentCount());//评论数量
    			result.add(feedDTO);
    		}
    	}
    	return result;
    }



	/**
	 * 通过用户id和消息id对一个feed进行封装
	 * */
	private FeedDTO feedProcess(Long userId,Feed feed){
		FeedDTO request = BeanMapper.map(feed, FeedDTO.class);
		Person person=personService.getPersonByUserId(feed.getUserId());
		User user=userService.getUserById(feed.getUserId());
		request.getCustomer().setMobile(user.getMobile());
		request.getCustomer().setName(user.getName());
		request.getCustomer().setPic(person.getAvatar());
		//处理pic
		String picStr = feed.getPics();
		if(StringUtils.isNotBlank(picStr)) {
			String[] pics = picStr.split("\\|");
			if(pics.length > 0) {
				request.setPicList(pics);
			}
		}
		/*评论数量*/
		Integer count=feedCommentDao.getFeedCommentCount(feed.getId());
		request.setCommentCount(count);
		//处理liked
		request.setLiked(false);
		if(userId != null) {
			FeedLike like = feedLikeDao.findByUserIdAndFeedId(userId, feed.getId());
			if(like != null) {
				request.setLiked(true);
			}
		}
		request.setCreateTime(feed.getCreateDate());
		//feedDTO.setCommentCount(feed.getCommentCount());//评论数量
		return request;
	}


	private List<FeedDTO> feedFamily(Long userId,List<Feed> feeds){
		List<FeedDTO> list=new ArrayList<>();
		if(feeds!=null && feeds.size()>0) {
			for (Feed feed:feeds) {
				FeedDTO request = BeanMapper.map(feed, FeedDTO.class);
				User user=userService.getUserById(feed.getUserId());
				if(user!=null) {
					request.getCustomer().setMobile(user.getMobile());
					request.getCustomer().setName(user.getName());
					request.getCustomer().setId(user.getId());
					Person person=personService.getPersonByUserId(user.getId());
					if(person!=null){
						request.getCustomer().setPic(person.getAvatar());
					}
				}
				//处理pic
				String picStr = feed.getPics();
				if (StringUtils.isNotBlank(picStr)) {
					String[] pics = picStr.split("\\|");
					if (pics.length > 0) {
						request.setPicList(pics);
					}
				}
				/*评论数量*/
				Integer count = feedCommentDao.getFeedCommentCount(feed.getId());
				request.setCommentCount(count);
				//评论内容
				List<FeedComment> comments=feedCommentDao.getFeedCommentList(feed.getId());
				List<FeedCommentDTO> feedCommentDTOList=new ArrayList<>();
				if(comments!=null){
					for (FeedComment feedComment:comments){
						FeedCommentDTO feedCommentDTO=new FeedCommentDTO();
						feedCommentDTO.setContent(feedComment.getContent());
						feedCommentDTO.setCreateTime(feedComment.getCreateDate().getTime());
						feedCommentDTO.setId(feedComment.getId());
						User u=userService.getUserById(feedComment.getUserId());
						feedCommentDTO.getCustomer().setName(u.getName());
						feedCommentDTO.getCustomer().setId(u.getId());
						feedCommentDTOList.add(feedCommentDTO);
					}
					request.setTopCommentList(feedCommentDTOList);
				}

				//处理liked
				request.setLiked(false);
				if (userId != null) {
					FeedLike like = feedLikeDao.findByUserIdAndFeedId(userId, feed.getId());
					if (like != null) {
						request.setLiked(true);
					}
				}
				request.setCreateTime(feed.getCreateDate());
				//feedDTO.setCommentCount(feed.getCommentCount());//评论数量
				list.add(request);
			}

		}
		return list;
	}

    /**
	 * 获取时间轴评论
	 * 
	 * @param id
	 * @param sinceId
	 * @param maxId
	 * @param pageSize
	 * @return
	 */
    public List<FeedCommentDTO> getCommentListTimeline(Long id, Long sinceId, Long maxId,
			Integer pageSize) {
    	Feed feed = feedDao.findOne(id);
		if (feed == null || EnumIsDelete.DELETED.getCode().equals(feed.getDeltag())) {
			throw new ServiceException(ResCode.FEED_NOT_EXIST);
		}
    	
    	List<FeedComment> feedComments = feedCommentDao.findTimeline(id, sinceId, maxId, pageSize);
    	List<FeedCommentDTO> result = new ArrayList<FeedCommentDTO>();
    	if(feedComments != null && !feedComments.isEmpty()) {
    		for (FeedComment entity : feedComments) {
    			FeedCommentDTO entityDTO = BeanMapper.map(entity, FeedCommentDTO.class);
				User user=userService.getUserById(entity.getUserId());
    			entityDTO.getCustomer().setMobile(user.getMobile());
				entityDTO.getCustomer().setName(user.getName());
				entityDTO.getCustomer().setId(user.getId());
				if(entity.getReplyUserid() != null) {
    				entityDTO.getReplyCustomer().setMobile(userService.getUserById(entity.getUserId()).getMobile());
    			}
    			entityDTO.setCreateTime(entity.getCreateDate().getTime());
    			result.add(entityDTO);
    		}
    	}
    	return result;
	}
    
    /**
	 * 获取详情信息
	 * 
	 * @param id
	 * @param customerId
	 * @return
	 */
	public FeedDTO getFeedById(Long id, Long customerId) {
		Feed feed = feedDao.findOne(id);
		if (feed == null || EnumIsDelete.DELETED.getCode().equals(feed.getDeltag())) {
			throw new ServiceException(ResCode.FEED_NOT_EXIST);
		}
		
		FeedDTO feedDTO = BeanMapper.map(feed, FeedDTO.class);
		
		feedDTO.getCustomer().setMobile(userService.getUserById(feed.getUserId()).getMobile());
		feedDTO.setCreateTime(feed.getCreateDate());
		
		//图片
		String picStr = feed.getPics();
		if(StringUtils.isNotBlank(picStr)) {
			String[] pics = picStr.split("\\|");
			if(pics.length > 0) {
				feedDTO.setPicList(pics);
			}
		}
		
		//处理liked
		feedDTO.setLiked(false);
		if(customerId != null) {
			FeedLike like = feedLikeDao.findByUserIdAndFeedId(customerId, feed.getId());
			if(like != null) {
				feedDTO.setLiked(true);
			} 
		}
		
		return feedDTO;
	}
    
    /**
	 * 赞
	 * 
	 * @param customerId
	 * @param id
	 * @return
	 */
	public Long createLike(Long customerId, Long id) {
		FeedLike like = feedLikeDao.findByUserIdAndFeedId(customerId, id);
		if(like == null) {
			like = new FeedLike();
			like.setUserId(customerId);
			like.setFeedId(id);
			like.setCreateDate(new Date());
			like.setUpdateDate(new Date());
			feedLikeDao.save(like);
		}
			//添加讨论的赞数
			Feed feed = feedDao.findOne(id);
			if(feed == null || EnumIsDelete.DELETED.getCode().equals(feed.getDeltag())) {
				//提示已经删除
				throw new ServiceException(ResCode.FEED_NOT_EXIST);
			}
		 	feed.setLikeCount(feed.getLikeCount() + 1);
			feedDao.save(feed);


		return like.getId();//原来的写法
		 //return like.getUserId();
	}
	
	/**
	 * 取消赞
	 * 
	 * @param customerId
	 * @param id
	 */
	public void delLike(Long customerId, Long id) {
		FeedLike like = feedLikeDao.findByUserIdAndFeedId(customerId, id);
		if(like != null) {
			feedLikeDao.delete(like);
			//删除讨论的赞数
			Feed feed = feedDao.findOne(id);
			if(feed == null || EnumIsDelete.DELETED.getCode().equals(feed.getDeltag())) {
				//提示已经删除
				throw new ServiceException(ResCode.FEED_NOT_EXIST);
			}
			feed.setLikeCount(feed.getLikeCount() - 1);
			feedDao.save(feed);
		}
		
	}
	
	/**
	 * 删除feed
	 * 
	 * @param customerId
	 * @param id
	 */
	public void delFeed(Long customerId, Long id) {
		User customer =userService.getUserById(customerId);
		if(customer == null || EnumIsDelete.DELETED.getCode().equals(customer.getDeltag())) {
			throw new ServiceException(ResCode.MGR_FEED_EMPTY_CUSTOMER);
		}
		
		Feed feed = feedDao.findOne(id);
		if(feed == null || EnumIsDelete.DELETED.getCode().equals(feed.getDeltag())) {
			//提示已经删除
			throw new ServiceException(ResCode.FEED_NOT_EXIST);
		}
		
		feed.setDeltag(EnumIsDelete.DELETED.getCode());
		feed.setIsTop(false);
		feed.setTopDate(null);
		feedDao.save(feed);
	}
	
	/**
	 * 删除评论
	 * 
	 * @param customerId
	 * @param commentId
	 */
	public void delComment(Long customerId, Long commentId) {
        User customer =userService.getUserById(customerId);
		if(customer == null || EnumIsDelete.DELETED.getCode().equals(customer.getDeltag())) {
			throw new ServiceException(ResCode.MGR_FEED_EMPTY_CUSTOMER);
		}
		
		FeedComment comment = feedCommentDao.findOne(commentId);
		
		if(comment == null || EnumIsDelete.DELETED.getCode().equals(comment.getDeltag())) {
			//提示已经删除
			throw new ServiceException(ResCode.FEED_COMMENT_NOT_EXIST);
		}
		
		comment.setDeltag(EnumIsDelete.DELETED.getCode());
		feedCommentDao.save(comment);
		
		//
		deleteCommentFeedProcess(comment.getFeed());
	}
	
	/**
	 *  创建Feed
	 * @param customerId
	 * @param tagId
	 * @param content
	 * @param pics
	 * @param cityName
	 * @param location
	 * @param latitude
	 * @param longitude
	 * @return
	 */
	public FeedDTO createFeed(Long customerId, Long tagId, String content,
			String pics, String cityName, String location, Double latitude, Double longitude) {
		//内容和图片不能同时为空
		/*if(StringUtils.isBlank(content) && StringUtils.isBlank(pics)) {
			throw new ServiceException(ResCode.ERROR_PARAM);
		}*/
		
		Feed feed = new Feed();
       User customer =userService.getUserById(customerId);
		/*if(customer == null || EnumIsDelete.DELETED.getCode().equals(customer.getDeltag())) {
			throw new ServiceException(ResCode.COMMON_CUSTOMER_NO_PERMISSION);
		}*/

		feed.setUserId(customerId);
	/*	if(customer.getFamilyid()!=0L ) {
			feed.setfId(customer.getFamilyid());
		}*/
		FeedTag tag = feedTagDao.findOne(tagId);
		/*if(tag == null || tag.getState() != 2) {
			throw new ServiceException(ResCode.FEED_TAG_NOT_EXIST);
		}*/
		feed.setFeedTag(tag);
		
		feed.setPics(pics);
		feed.setCityName(cityName);
		feed.setLocation(location);
		feed.setContent(content);
		feed.setLatitude(latitude);
		feed.setLongitude(longitude);
		
		feed.setComments(null);
		feed.setLikeCount(0);
		feed.setCommentCount(0);
		feed.setReportCount(0);
		feed.setShareCount(0);
		feed.setViewCount(0);
		feed.setState(0);
		feed.setDeltag(EnumIsDelete.NOTDELETE.getCode());
		Date now = new Date();
		feed.setCreateDate(now);
		feed.setUpdateDate(now);
		feedDao.save(feed);
		
		FeedDTO result = BeanMapper.map(feed, FeedDTO.class);
		//转换图片
	/*	if(StringUtils.isNotBlank(pics)) {
			String[] picsArray = pics.split("\\|");
			if(picsArray.length > 0) {
				result.setPicList(picsArray);
			}
		}*/
		
		result.getCustomer().setMobile(customer.getMobile());
		result.setLiked(false);
		result.setCreateTime(now);
		//2016-12-22 修改，发布帖子不再增加积分
//		customerTaskActiveService.saveIntegration(customer.getId(), EnumTaskType.CHAT.getCode());
		return result;
	}

	/*
	* 个人页面里的历程增加  参照feed

	*
	* */
	
	/**
	 * 创建评论
	 * 
	 * @param customerId
	 * @param replyCustomerId
	 * @param id
	 * @param content
	 * @return
	 */
	public FeedCommentDTO createComment(Long customerId,
			Long replyCustomerId, Long id, String content) {
		String tag="2";
		FeedComment comment = new FeedComment();
        User customer =userService.getUserById(customerId);
		if(customer == null || EnumIsDelete.DELETED.getCode().equals(customer.getDeltag())) {
			throw new ServiceException(ResCode.COMMON_CUSTOMER_NO_PERMISSION);
		}
		comment.setUserId(customerId);

		if(replyCustomerId == null) {
			comment.setReplyUserid(null);
		} else {
            User replyCustomer =userService.getUserById(customerId);
			if(replyCustomer == null || EnumIsDelete.DELETED.getCode().equals(replyCustomer.getDeltag())) {
				throw new ServiceException(ResCode.FEED_REPLY_CUSTOMER_NO_PERMISSION);
			}
			comment.setReplyUserid(customerId);
		}
		
		Feed feed = feedDao.findOne(id);
		if(feed == null || EnumIsDelete.DELETED.getCode().equals(feed.getDeltag())) {
			//提示已经删除
			throw new ServiceException(ResCode.FEED_NOT_EXIST);
		}else{
			//如果自己评论 则不发消息
			if(feed.getUserId()==customerId){
				tag="0";
			}
		}
		comment.setFeed(feed);
		comment.setContent(content);
		comment.setState(0);
		comment.setDeltag(EnumIsDelete.NOTDELETE.getCode());
		Date now = new Date();
		comment.setCreateDate(now);
		comment.setUpdateDate(now);
		feedCommentDao.save(comment);

		FeedCommentDTO result = BeanMapper.map(comment, FeedCommentDTO.class);
		result.getCustomer().setMobile(customer.getMobile());
		if(comment.getReplyUserid() != null) {
			result.getReplyCustomer().setMobile(userService.getUserById(comment.getUserId()).getMobile());
//			result.getCustomer().setId(userService.getUserById(comment.getUserId()).getId());
			result.getCustomer().setName(userService.getUserById(comment.getUserId()).getName());
		}
		result.setCreateTime(now.getTime());
		
		//添加讨论的评论数
		feed.setCommentCount(feed.getCommentCount() + 1);
		
		//最晚4条
		String topCommentsStr = feed.getComments();
		JsonMapper mapper = JsonMapper.nonDefaultMapper();
		List<FeedCommentDTO> topComments = (List<FeedCommentDTO>) mapper.fromJson(topCommentsStr, mapper.contructCollectionType(List.class, FeedCommentDTO.class));
		if(topComments == null) {
			topComments = new ArrayList<FeedCommentDTO>();
		}
		topComments.add(0, result);
		if(topComments.size() == 5) {
			topComments.remove(4);
		}
		
		topCommentsStr = mapper.toJson(topComments);
		
		feed.setComments(topCommentsStr);
		feedDao.save(feed);
//		if(tag.equals("1")){
//			TruckMessage tm = new TruckMessage();
//			tm.setCreatedate(new Date());
//	        tm.setDeltag(EnumIsDelete.NOTDELETE.getCode());
//	        tm.setDevice(EnumJpushTag.BOTH.getCode());
//	        tm.setCustomor(feed.getCustomer());
//	        tm.setMsg("您的帖子有最新的评论！");
//	        tm.setMode(EnumTruckAuditStatus.COMMENT.getCode());
//	        TruckMessage message = messageService.saveTruckMessage(tm);
//	        if(message != null)
//	        {
//	            TruckMessageUser user = new TruckMessageUser();
//	            user.setCreatedate(new Date());
//	            user.setCustomor(feed.getCustomer());
//	            user.setDeltag(EnumIsDelete.NOTDELETE.getCode());
//	            user.setIsread("0");
//	            user.setTruckMessage(message);
//	            user.setUpdatedate(new Date());
//	            messageUserService.saveTruckMessageUser(user);
//	        }
//	        String str="尊敬的用户您发布的帖子，有最新的评论，请点击查看";
//	        JPushUtil.pushAllByAliasByPuchase("000000" +feed.getCustomer().getId(), str, EnumJpushTag.BOTH.getCode(),id,EnumTruckAuditStatus.COMMENT.getName());
//		}
		return result;
	}
	/**
	 * 分页查询贴子评论
	 * @param feedId
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 */
	public Page<FeedComment> findPageComment(Long feedId,Integer pageNumber,Integer pageSize){
		List<FeedComment> feedCommentList =feedCommentDao.findPageComment(feedId, pageNumber, pageSize);
		Pageable pageable=new PageRequest(pageNumber-1,pageSize);
		Long total =feedCommentDao.getTotalCount(feedId);
		Page<FeedComment> page=new PageImpl<FeedComment>(feedCommentList,pageable,total);
		return page;
	}
	/**
	 * 分页查询贴子点赞
	 * @param feedId
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 */
	public Page<Object[]> findPageLikeLoginName(Long feedId,Integer pageNumber,Integer pageSize){
		List<Object[]> feedLikeList =feedLikeDao.findPageLikeLoginName(feedId, pageNumber, pageSize);
		Pageable pageable=new PageRequest(pageNumber-1,pageSize);
		Long total =feedLikeDao.getTotalCount(feedId);
		Page<Object[]> page=new PageImpl<Object[]>(feedLikeList,pageable,total);
		return page;
	}
	
	/**
	 * 删除评论
	 * @param id 评论id
	 * @return
	 */
	public FeedComment deleteFeedComment(Long id) {
		FeedComment comment=feedCommentDao.findOne(id);
		comment.setDeltag(EnumIsDelete.DELETED.getCode());
		
		StringBuilder content = new StringBuilder();
		content.append("【");
		content.append(comment.getCreateDate());
		content.append("】 评论 【");
		content.append(comment.getContent());
		content.append("】 ");
		FeedMsg msg = new FeedMsg(id, comment.getUserId(),
				2, 1, content.toString(), new Date());
		feedMsgDao.save(msg);
		comment = feedCommentDao.save(comment);
		deleteCommentFeedProcess(comment.getFeed());
		return comment;
	}
	
	private void deleteCommentFeedProcess(Feed feed) {
		if(feed == null || EnumIsDelete.DELETED.getCode().equals(feed.getDeltag())) {
			//提示已经删除
			throw new ServiceException(ResCode.FEED_NOT_EXIST);
		}
		
		feed.setCommentCount(feed.getCommentCount() - 1);
		
		//处理comment str
		if(feed.getCommentCount() == 0) {
			feed.setComments(null);
		} else {
			//还可以优化一下，现在直接查最新4条更新上去。
			List<FeedComment> comments = feedCommentDao.findTimeline(feed.getId(), null, null, 4);
			if(comments != null && !comments.isEmpty()) {
				List<FeedCommentDTO> dtos = new ArrayList<FeedCommentDTO>();
				for (FeedComment entity : comments) {
					FeedCommentDTO entityDTO = BeanMapper.map(entity, FeedCommentDTO.class);
					entityDTO.setCreateTime(entity.getCreateDate().getTime());
					entityDTO.getCustomer().setMobile(userService.getUserById(entity.getUserId()).getMobile());
					if(entity.getReplyUserid() != null) {
	    				entityDTO.getReplyCustomer().setMobile(userService.getUserById(entity.getReplyUserid()).getMobile());
	    			}
					dtos.add(entityDTO);
				}
				JsonMapper mapper = JsonMapper.nonDefaultMapper();
				feed.setComments(mapper.toJson(dtos));
			} else {
				feed.setComments(null);
			}
		}
		
		feedDao.save(feed);
	}
	
	/**
	 * ----- 举报数 ----属性最好要在feed中，暂时先这样子吧。 两种业务关联太紧。
	 * 增加feed 举报数
	 * 
	 * @param feedId
	 */
	public void addFeedReportCount(Long feedId) {
		Feed feed = feedDao.findOne(feedId);
		if(feed == null || EnumIsDelete.DELETED.getCode().equals(feed.getDeltag())) {
			//提示已经删除
			throw new ServiceException(ResCode.FEED_NOT_EXIST);
		}
		feed.setReportCount(feed.getReportCount() + 1);
		feedDao.save(feed);
	}
	
	/**
	 * 获取删除记录的消息
	 * 
	 * @param customerId
	 * @param pageSize
	 * @return
	 */
    public List<FeedMsgDTO> getFeedMsgList(Long customerId, Integer pageSize) {
    	 List<FeedMsg> msgs = feedMsgDao.findTimeline(customerId, pageSize);
    	 List<FeedMsgDTO> result = BeanMapper.mapList(msgs, FeedMsgDTO.class);
    	 if(result == null) {
    		 result = new ArrayList<FeedMsgDTO>();
    	 }
    	 return result;
	}
    
    /**
     * 置顶和取消置顶
     * 
     * @param id
     * @param top
     */
    public void setTop(Long id, Boolean top) {
    	Feed feed = feedDao.findOne(id);
    	//如果帖子已经被删除或者不存在
    	if(feed == null || EnumIsDelete.DELETED.getCode().equals(feed.getDeltag())) {
			throw new ServiceException(ResCode.MGR_FEED_NOT_EXIST);
		}
    	if(feed.getIsTop() != top) {
    		BigDecimal count = feedDao.getTopCount();
    		//如果置顶且大于等于2个
    		if(top) {
    			if(count.intValue() >= 2) {
    				throw new ServiceException(ResCode.MGR_FEED_SETTOP_OVER_LIMIT);
    			}
    			feed.setTopDate(new Date());
    		} else {
    			feed.setTopDate(null);
    		}
    		feed.setIsTop(top);
    		feed.setUpdateDate(new Date());
    		feedDao.save(feed);
    	}
    	
    }


	/**
	 * 获取帖子点赞总数量
	 * @param feedId 帖子Id
	 * @param userId 用户id
	 * @return 帖子评论总数量
	 * */
	public Integer getFeedCommentCount(Long feedId,Long userId){
		return feedCommentDao.getFeedCommentCount(feedId);
	}

	public List<Feed> getFeedListByFamily(Long familyid) {
		return feedDao.getFeedListByFamily(familyid);
	}

	/*
	* 倒叙查询贴子
	* 所有
	* */
	public List<Feed> findFeedAll(){
		return feedDao.findFeedAll();

	}

}
